import React, { useEffect, useState } from 'react';
import { Card, Button, Table, Modal, Form, Input, message, Popconfirm, Tabs } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, TeamOutlined, ProjectOutlined } from '@ant-design/icons';
import { useAuth } from '../../hooks/useAuth';
import { workspaceAPI } from '../../api/workspace';
import { WorkspaceMemberList } from '../../components/workspace/WorkspaceMemberList';
import type { Workspace } from '../../types/api';

const { TabPane } = Tabs;

const WorkspacePage: React.FC = () => {
  const { user } = useAuth();
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingWorkspace, setEditingWorkspace] = useState<Workspace | null>(null);
  const [selectedWorkspace, setSelectedWorkspace] = useState<Workspace | null>(null);
  const [activeTab, setActiveTab] = useState('list');
  const [form] = Form.useForm();

  // 加载工作区列表
  const loadWorkspaces = async () => {
    setLoading(true);
    try {
      const response = await workspaceAPI.getMyWorkspaces();
      if (response.success && Array.isArray(response.data)) {
        setWorkspaces(response.data);
      } else {
        message.error('获取工作区列表失败');
      }
    } catch (error) {
      console.error('加载工作区失败:', error);
      message.error('加载工作区失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadWorkspaces();
  }, []);

  // 创建或更新工作区
  const handleSubmit = async (values: any) => {
    try {
      if (editingWorkspace) {
        // 更新工作区
        const response = await workspaceAPI.updateWorkspace(editingWorkspace.id, values);
        if (response.success) {
          message.success('工作区更新成功');
          loadWorkspaces();
        }
      } else {
        // 创建工作区
        const response = await workspaceAPI.createWorkspace(values);
        if (response.success) {
          message.success('工作区创建成功');
          loadWorkspaces();
        }
      }
      setModalVisible(false);
      form.resetFields();
      setEditingWorkspace(null);
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  // 删除工作区
  const handleDelete = async (id: string) => {
    try {
      const response = await workspaceAPI.deleteWorkspace(id);
      if (response.success) {
        message.success('工作区删除成功');
        loadWorkspaces();
        if (selectedWorkspace?.id === id) {
          setSelectedWorkspace(null);
          setActiveTab('list');
        }
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 编辑工作区
  const handleEdit = (workspace: Workspace) => {
    setEditingWorkspace(workspace);
    form.setFieldsValue(workspace);
    setModalVisible(true);
  };

  // 查看工作区详情
  const handleViewDetails = (workspace: Workspace) => {
    setSelectedWorkspace(workspace);
    setActiveTab('details');
  };

  // 表格列定义
  const columns = [
    {
      title: '工作区名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Workspace) => (
        <Button type="link" onClick={() => handleViewDetails(record)}>
          {text}
        </Button>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Workspace) => (
        <div className="space-x-2">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个工作区吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const renderContent = () => {
    switch (activeTab) {
      case 'list':
        return (
          <Card
            title="工作区管理"
            extra={
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  setEditingWorkspace(null);
                  form.resetFields();
                  setModalVisible(true);
                }}
              >
                创建工作区
              </Button>
            }
          >
            <Table
              columns={columns}
              dataSource={workspaces}
              rowKey="id"
              loading={loading}
            />
          </Card>
        );
      case 'details':
        if (!selectedWorkspace) return null;
        return (
          <div className="space-y-6">
            <Card>
              <div className="flex justify-between items-center mb-4">
                <div>
                  <h2 className="text-2xl font-bold">{selectedWorkspace.name}</h2>
                  <p className="text-gray-500">{selectedWorkspace.description}</p>
                </div>
                <div className="space-x-2">
                  <Button
                    icon={<EditOutlined />}
                    onClick={() => handleEdit(selectedWorkspace)}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    title="确定要删除这个工作区吗？"
                    onConfirm={() => handleDelete(selectedWorkspace.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button danger icon={<DeleteOutlined />}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-gray-500">创建时间</p>
                  <p>{new Date(selectedWorkspace.createdAt).toLocaleString()}</p>
                </div>
                <div>
                  <p className="text-gray-500">更新时间</p>
                  <p>{new Date(selectedWorkspace.updatedAt).toLocaleString()}</p>
                </div>
              </div>
            </Card>

            <Card 
              title={
                <span>
                  <TeamOutlined className="mr-2" />
                  成员管理
                </span>
              }
            >
              <WorkspaceMemberList workspaceId={selectedWorkspace.id} />
            </Card>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="p-6">
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        className="mb-6"
      >
        <TabPane
          tab={
            <span>
              <ProjectOutlined />
              工作区列表
            </span>
          }
          key="list"
        />
        {selectedWorkspace && (
          <TabPane
            tab={
              <span>
                <TeamOutlined />
                {selectedWorkspace.name}
              </span>
            }
            key="details"
          />
        )}
      </Tabs>

      {renderContent()}

      <Modal
        title={editingWorkspace ? '编辑工作区' : '创建工作区'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingWorkspace(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        okText="确定"
        cancelText="取消"
        okButtonProps={{ type: 'primary', style: { backgroundColor: '#1890ff' } }}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="工作区名称"
            rules={[{ required: true, message: '请输入工作区名称' }]}
          >
            <Input placeholder="请输入工作区名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入工作区描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default WorkspacePage; 